package com.example.nio.example;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SockeChannelExample {
    public static void open()throws Exception{
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        serverSocketChannel.socket().bind(new InetSocketAddress(9999));

        while(true){
            SocketChannel socketChannel =
                serverSocketChannel.accept();
            ByteBuffer buf = ByteBuffer.allocate(1000);
            int bytesRead = socketChannel.read(buf);
            while (bytesRead != -1) {
                System.out.println("Read " + bytesRead);
                buf.flip();
                while(buf.hasRemaining()){
                    System.out.print((char) buf.get());
                }
                buf.clear();
                bytesRead = socketChannel.read(buf);
            }
        }
    }

    public static void client() throws IOException {
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1",9999));
        ByteBuffer writeBuffer=ByteBuffer.wrap("12312".getBytes("UTF-8"));
        socketChannel.write(writeBuffer);
    }

    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        executorService.execute(() -> {
            try {
                open();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        Thread.sleep(1000L);
        executorService.execute(() -> {
            try {
                client();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
}
